using ERPBackend.Data;
using ERPBackend.Models;
using ERPBackend.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.Threading.Tasks;
using System;
using System.Linq;

namespace ERPBackend.Services
{
    public class WorkshopService : IWorkshopService
    {
        private readonly ApplicationDbContext _context;
        private readonly ILogger<WorkshopService> _logger;

        public WorkshopService(ApplicationDbContext context, ILogger<WorkshopService> logger)
        {
            _context = context;
            _logger = logger;
        }

        public async Task<IEnumerable<Workshop>> GetAllWorkshopsAsync()
        {
            try
            {
                return await _context.Workshops
                    .Include(w => w.Department)
                    .Include(w => w.Manager)
                    .ToListAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error occurred while getting all workshops");
                throw;
            }
        }

        public async Task<Workshop?> GetWorkshopByIdAsync(int id)
        {
            try
            {
                return await _context.Workshops
                    .Include(w => w.Department)
                    .Include(w => w.Manager)
                    .FirstOrDefaultAsync(w => w.Id == id);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error occurred while getting workshop by id: {Id}", id);
                throw;
            }
        }

        public async Task<Workshop> CreateWorkshopAsync(Workshop workshop)
        {
            try
            {
                // Check if workshop code already exists
                if (await _context.Workshops.AnyAsync(w => w.WorkshopCode == workshop.WorkshopCode))
                {
                    throw new ArgumentException("Workshop code already exists");
                }

                _context.Workshops.Add(workshop);
                await _context.SaveChangesAsync();
                return workshop;
            }
            catch (ArgumentException ex)
            {
                _logger.LogWarning(ex, "Duplicate workshop code: {WorkshopCode}", workshop.WorkshopCode);
                throw;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error occurred while creating workshop");
                throw;
            }
        }

        public async Task<bool> UpdateWorkshopAsync(Workshop workshop)
        {
            try
            {
                // Check if workshop exists
                var existingWorkshop = await _context.Workshops.FindAsync(workshop.Id);
                if (existingWorkshop == null)
                {
                    return false;
                }

                // Check if workshop code is being changed and if new code already exists
                if (existingWorkshop.WorkshopCode != workshop.WorkshopCode &&
                    await _context.Workshops.AnyAsync(w => w.WorkshopCode == workshop.WorkshopCode && w.Id != workshop.Id))
                {
                    throw new ArgumentException("Workshop code already exists");
                }

                // Update workshop properties
                _context.Entry(existingWorkshop).CurrentValues.SetValues(workshop);
                await _context.SaveChangesAsync();
                return true;
            }
            catch (ArgumentException ex)
            {
                _logger.LogWarning(ex, "Duplicate workshop code: {WorkshopCode}", workshop.WorkshopCode);
                throw;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error occurred while updating workshop with id: {Id}", workshop.Id);
                throw;
            }
        }

        public async Task<bool> DeleteWorkshopAsync(int id)
        {
            try
            {
                var workshop = await _context.Workshops.FindAsync(id);
                if (workshop == null)
                {
                    return false;
                }

                // Check if there are any related production orders
                // This is a placeholder - you should add actual checks based on your data model
                // if (await _context.ProductionOrders.AnyAsync(po => po.WorkshopId == id))
                // {
                //     throw new InvalidOperationException("Cannot delete workshop with related production orders");
                // }

                _context.Workshops.Remove(workshop);
                await _context.SaveChangesAsync();
                return true;
            }
            catch (InvalidOperationException ex)
            {
                _logger.LogWarning(ex, "Cannot delete workshop with id: {Id}", id);
                throw;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error occurred while deleting workshop with id: {Id}", id);
                throw;
            }
        }

        public async Task<bool> ChangeWorkshopStatusAsync(int id, byte status)
        {
            try
            {
                var workshop = await _context.Workshops.FindAsync(id);
                if (workshop == null)
                {
                    return false;
                }

                workshop.Status = status;
                await _context.SaveChangesAsync();
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error occurred while changing status of workshop with id: {Id}", id);
                throw;
            }
        }
    }
}